import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import { ListTranslator, TerModel } from './translator'
import { differenceBy } from 'lodash-es'
import Alert from '@/components/Alert'
import { fetchStopSelectView, fetchStartSelectView } from '@/api/manager/select'
import { SelectInfoEntity, SelectViewParamsEntity } from '@/api/manager/select/interface'
import { useMccStore } from '../../store'
import { MtEntity } from '@/api/manager/mt'
import { useTableAllStore } from '../main/table/all/store'
import { getItemByMtKey } from '../main/table/all/utils'

type StateStore = {
	/**数据备份*/
	dataBackups: Array<SelectInfoEntity>
	/**选看模式 1-视频;2-音视频;*/
	media_mode: 1 | 2
	/**模式展示列表 */
	mediaModeList: Array<{ label: string; value: number }>
	/**被选看终端信息 */
	src_account: MtEntity | null
	/**当前被选看终端信息 */
	current_src_account: Array<TerModel>
	/**被选看终端信息 */
	src_account_list: Array<TerModel>
	/**选看终端信息 */
	des_account: MtEntity | null
	/**选看终端信息 */
	des_account_list: Array<TerModel>
	/**消息推送的值 */
	is_mcc_meeting_selectview: any
	_start: string
	_changes: string[]
	/**此字段是为了左侧表格直接操作添加到选看*/
	/** 是否左侧列表推送 */
	is_call_back: boolean
	/** 左测推送终端 */
	is_call_back_mt: Array<MtEntity>
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	addListDes: (_list: MtEntity[]) => void
	removeLi: (mtKeys: string[]) => void
	removeDesMt: (mtKey: string) => void
	removeSrcMt: (mtKey: string) => void
	updateList: (updateList: MtEntity) => void
	toggleClick: (mtKey: string) => void
	/**获取选看终端对应的被选看终端 */
	getDesToSrc: (mtKey: string) => void
	updateMode: (media_mode: 1 | 2) => void
	/**清空页面 */
	clearPage: () => void
	/**消息处理 */
	msgHandle: (data: SelectInfoEntity) => void
	selectMt: () => void
	removeSelectMt: (mtKey: string) => void
}
const initialState: StateStore = {
	mediaModeList: [
		{ label: t('视频选看'), value: 1 },
		{ label: t('音视频选看'), value: 2 },
	],
	media_mode: 1,
	src_account: null,
	src_account_list: [],
	current_src_account: [],
	des_account: null,
	des_account_list: [],
	dataBackups: [],
	is_mcc_meeting_selectview: null,
	_start: '',
	_changes: [],
	is_call_back: false,
	is_call_back_mt: [],
}
export const store = createVanilla<IStore>((set, get) => ({
	...initialState,
	update: (d) => set({ ...d }),
	reset: () => set(initialState),
	/** 修改音视频选看 */
	updateMode: async (media_mode: 1 | 2) => {
		const { _start, update, dataBackups } = get()
		if (!_start) {
			update({ media_mode: media_mode })
		} else {
			const item = dataBackups.find((item) => {
				return item.des_account?.mt_key === _start
			})
			if (!item?.src_account?.mt_key) {
				update({ media_mode: media_mode })
			} else {
				const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
				const params = {
					dst_account: _start,
					src_account: item.src_account.mt_key,
					flag: 0,
					media_mode: media_mode,
				}
				const res = await fetchStartSelectView(meetingMoid, params)
				if (!res.success) {
					if (res.error_code === 20435) {
						let tree = useTableAllStore.getState().tree
						let src_account = getItemByMtKey(tree, item.src_account.mt_key)?.mcc
						let dst_account = getItemByMtKey(tree, _start)?.mcc
						let arr = []
						let text_src = src_account && !src_account?.status.isOnline ? src_account.name : ''
						let text_dst = dst_account && !dst_account?.status.isOnline ? dst_account.name : ''
						arr.push(text_src, text_dst)
						let _arr = arr.filter((item) => item)
						Alert(t('您指定的{{name}}不在您的会议中(20435)', { name: _arr.join(',') }))
					} else {
						Alert(res.description || t('切换失败'))
					}
				}
			}
		}
	},
	/**新增终端(选看)*/
	addListDes: (addList) => {
		const { des_account_list } = get()
		let mts = ListTranslator(addList)
		const insertList = differenceBy(mts, des_account_list, (x) => x.mtKey)
		set({
			des_account_list: [
				...des_account_list.slice(0, des_account_list.length),
				...insertList,
				...des_account_list.slice(des_account_list.length),
			],
		})
	},
	/**移除选看终端*/
	removeLi: async (mtKeys) => {
		const { dataBackups, des_account_list } = get()
		const item = dataBackups.find((item) => {
			return mtKeys.includes(item.des_account?.mt_key || '')
		})
		if (!item) {
			/**拖拽进入选看终端  然后删除这个终端的情况*/
			const unRemove = des_account_list.filter((l) => !mtKeys.includes(l.mtKey))
			/** 需要判断是否存在选在 */
			set({ des_account_list: unRemove })
			return
		}
	},
	/**移除选看终端*/
	removeDesMt: async (mtKey) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const { dataBackups, des_account_list, selectMt } = get()
		const item = dataBackups.find((item) => {
			return item.des_account?.mt_key === mtKey
		})
		if (!item) {
			/**拖拽进入选看终端  然后删除这个终端的情况*/
			const unRemove = des_account_list.filter((l) => l.mtKey !== mtKey)
			/** 需要判断是否存在选在 */
			set({ des_account_list: unRemove })
			selectMt()
			return
		}
		const params: SelectViewParamsEntity = {
			src_account: item?.src_account?.mt_id || '',
			dst_account: item?.des_account?.mt_id || '',
			media_mode: item?.media_mode || 1,
			flag: 0,
		}
		const success = await fetchStopSelectView(meetingMoid, params)
		!success && Alert(t('取消选看失败'))
	},
	removeSelectMt: (mt_key: string) => {
		const { dataBackups, des_account_list, _start } = get()
		const unRemoveList = des_account_list.filter((item) => item.mtKey !== mt_key)
		const unRemoveDataBackups = dataBackups.filter((item) => item.des_account?.mt_key !== mt_key)
		if (_start === mt_key) {
			set({ _start: '' })
		}
		set({ des_account_list: [...unRemoveList], dataBackups: [...unRemoveDataBackups], src_account_list: [] })
	},
	/**移除被选看终端*/
	removeSrcMt: async (mtKey) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const { dataBackups } = get()
		const item = dataBackups.find((item) => {
			return item.src_account?.mt_key === mtKey
		})
		const params: SelectViewParamsEntity = {
			src_account: item?.src_account?.mt_id || '',
			dst_account: item?.des_account?.mt_id || '',
			media_mode: item?.media_mode || 1,
			flag: 0,
		}
		const success = await fetchStopSelectView(meetingMoid, params)
		!success && Alert(t('取消选看失败'))
	},
	selectMt: () => {
		const { des_account_list, src_account_list, toggleClick } = get()
		/**（1）选看终端不存在终端被选中 ;选看终端列表不为空*/
		/**（2）选看终端存在终端选中 ;被选看终端列表为空*/
		/**选中第一条数据 */
		const checkedList = des_account_list.filter((item) => item.status.checked).length
		if (
			(checkedList === 0 && des_account_list.length > 0) ||
			(checkedList === 1 && src_account_list.length === 0)
		) {
			const mt_key = des_account_list[0].mtKey
			toggleClick(mt_key)
		}
	},
	msgHandle: (source) => {
		//1.选看终端存在，而被选看不存在，要删除desSrcMts数组中选看终端信息(删除终端)
		//2.选看终端在desSrcMts不存在，并且被选看终端信息不为空,desSrcMts增加这一项(添加终端)
		//3.选看终端存在，被选看终端与desSrcMts保存的被选看不同，更新desSrcMts(修改终端信息)
		//4.只修改选看模式
		//5.新增情况 删除与会终端 选看终端在会场被删除
		const { des_account, src_account, media_mode } = source
		const { selectMt, addListDes, _start, toggleClick, dataBackups, removeSelectMt, des_account_list } = get()
		if (!des_account /**第五种情况 */) {
			/**初始化*/
			set({ is_mcc_meeting_selectview: {} })
			selectMt()
			return false
		}
		/**判断选看终端是否备份列表当中(备份数据找不到就是新增) */
		if (des_account && media_mode && src_account && src_account.mt_key /**推送终端信息完全*/) {
			/**判断选看终端是否备份列表当中*/
			const flag_backups = get().dataBackups.findIndex((item) => item.des_account?.mt_key === des_account.mt_key)
			if (flag_backups < 0) {
				/**更新备份数据 */
				set({ dataBackups: [...dataBackups, source] })
				/**新增选看终端 */
				addListDes([des_account])
				/**如果增加选看终端是最后一次点击终端，则选中该条目*/
				_start === des_account.mt_id ? toggleClick(_start) : selectMt()
				return false
			}
		}

		/**判断选看终端是否存在列表当中*/
		const flag = des_account_list.findIndex((item) => item.mtKey === des_account.mt_key)
		for (let i = 0; i < des_account_list.length; i++) {
			let involve = false
			if (des_account_list[i]?.mcc.mtid === des_account.mt_id) {
				involve = true
				//@1 选看终端存在  被选看终端不存在
				if (!src_account?.mt_id) {
					removeSelectMt(des_account.mt_key)
				}
				/**以下其实做更新操作*/
				const _item = get().dataBackups.find((x) => x.des_account?.mt_key === des_account.mt_key)
				if (_item && src_account && flag > -1) {
					if (_item?.src_account?.mt_key !== src_account?.mt_key) {
						//@3 选看终端存在  被选看终端不同
						_item.src_account = src_account
						_item.media_mode = media_mode
						if (des_account.mt_key === _start) {
							//修改当前选看终端 设置src_account_list为空触发刷新
							set({ dataBackups: [...dataBackups], src_account_list: ListTranslator([src_account]) })
						} else {
							set({ dataBackups: [...dataBackups] })
						}
					}
					//@4 选看终端存在  被选看终端相同 选看模式不同
					if (_item.src_account?.mt_key === src_account?.mt_key && _item.media_mode !== media_mode) {
						_item.media_mode = media_mode
						if (des_account.mt_key === _start) {
							set({ dataBackups: [...dataBackups], media_mode: media_mode || 1 })
						} else {
							set({ dataBackups: [...dataBackups] })
						}
					}
				}
			}
			!involve && !src_account?.mt_id && removeSelectMt(des_account.mt_key)
			selectMt()
		}
	},
	/**更新终端*/
	updateList: () => {},
	getDesToSrc: (mtKey) => {
		const { dataBackups } = get()
		const item = dataBackups.find((item) => {
			return item.des_account?.mt_key === mtKey
		})
		set({
			src_account_list: item?.src_account ? ListTranslator([item.src_account]) : [] /**被选看终端 */,
			media_mode: item?.media_mode || 1 /**被选看终端模式 */,
		})
	},
	toggleClick: (mtKey) => {
		const { des_account_list, getDesToSrc } = get()
		des_account_list.forEach((item: { mtKey: string; status: { checked: boolean } }) => {
			if (item.mtKey === mtKey) {
				item.status.checked = true
			} else {
				item.status.checked = false
			}
		})
		getDesToSrc(mtKey)
		set({ des_account_list: [...des_account_list], _start: mtKey, _changes: [] })
	},
	clearPage: () => {
		set({
			des_account_list: [] /**选看终端列表 */,
			dataBackups: [] /**备份数据 */,
			src_account_list: [] /**被选看终端列表 */,
		})
	},
}))
export const useSelectStore = create(store)
